package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	_ "golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"log"
	"math/rand"
	"time"

	"net/http"

	"zlxBook/Dao"
	"zlxBook/Response"
	"zlxBook/common"
	"zlxBook/db"
	"zlxBook/dto"
	"zlxBook/model"
)

func Register(context *gin.Context) {
	context.JSON(http.StatusOK, gin.H{
		"msg": "yes，接受请求",
	})
	name := context.PostForm("name")
	password := context.PostForm("password")
	phone := context.PostForm("phone")

	fmt.Println(name, password, phone)
	if len(phone) != 11 {
		context.JSON(http.StatusUnprocessableEntity, gin.H{
			"code":  422,
			"phone": phone,
			"msg":   "不支持的电话号码",
			"len":   len(phone),
		})
	}
	if len(password) < 6 {
		context.JSON(http.StatusUnprocessableEntity, gin.H{
			"msg":  "不支持的账号密码",
			"code": 422,
			"len":  len(password),
		})
	}
	if len(name) == 0 {
		name = RandomString(8)
	}
	context.JSON(http.StatusOK, gin.H{
		"msg": "Register Success!",
	})
	log.Println(name, password, phone)
	if Dao.CheckPhoneExist(phone) {
		context.JSON(http.StatusOK, gin.H{
			"msg": "该号码已经存在",
		})
		return
	}
	//密码加密
	hasedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	user := model.User{
		Model:    gorm.Model{},
		Name:     name,
		Password: string(hasedPassword),
		Phone:    phone,
	}
	err1 := db.DB.Create(&user).Error
	if err1 != nil {
		context.JSON(501, gin.H{"msg": "数据库错误"})
		fmt.Println(err1.Error())
	}

}

//准备登录
func Login(context *gin.Context) {
	//获取参数
	phone := context.PostForm("phone") // 获取参数
	password := context.PostForm("password")
	fmt.Println("收到请求")

	if len(phone) != 11 {

		context.JSON(http.StatusUnprocessableEntity, gin.H{
			"msg": "请输入正确的手机号",
			"输入为": phone,
		})
		panic("触发手机号错误")
		return
	}
	fmt.Println("HERE1")
	//判断是否有这个账号存在
	if !Dao.CheckPhoneExist(phone) {
		context.JSON(http.StatusUnprocessableEntity, gin.H{
			"msg": "没有这个账户",
		})
		return
	}
	fmt.Println("HERE")
	//数据验证
	user, err := Dao.GetUserByPhone(phone)
	if err != nil {
		context.JSON(http.StatusUnprocessableEntity, gin.H{
			"msg": "取数错误",
		})
		return
	}
	fmt.Println("HERE2")
	//判断密码正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { // 判断密码是否正确
		context.JSON(http.StatusOK, gin.H{"msg": "sad"})
		Response.Response(context, 400, 400, gin.H{"code": 400, "msg": "password err!",
			"psswprd":   user.Password,
			"password2": password,
			"msgs":      err.Error(),
		}, "password err")
		fmt.Println("HERE3")
	}
	token, _ := common.RealeaseToken(user)
	//返回结果

	context.JSON(http.StatusOK, gin.H{
		"msg": "成功登录",
	})
	context.JSON(http.StatusOK, gin.H{
		"status": "success create token!",
		"tokens": token,
	})

}

func RandomString(n int) string {
	var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	result := make([]byte, n)
	rand.Seed(time.Now().Unix())
	for k := range result {
		result[k] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}
func Info(context *gin.Context) {
	user, _ := context.Get("user")
	context.JSON(http.StatusOK, gin.H{
		"msg": "statusOk",
		"data": gin.H{
			"userIngo:": dto.ToUserDto(user.(model.User)),
		},
	})

}
